package D240523;

import java.util.Arrays;

public class MyStringBuilder {
    char[] value;

    public MyStringBuilder() {

    }

    public MyStringBuilder(String string) {
        value = string.toCharArray();
    }

    public MyStringBuilder append(String string) {
        char[] temp = string.toCharArray();

        // 核心内容：如何将旧数组搬运至新数组实现数组的扩充

        // 1.使用循环复制
        /*
        for (int i = 0; i < value.length; i++) {
            result[i] = value[i];
        }
        for (int i = 0; i < temp.length; i++) {
            result[i + value.length] = temp[i];
        }
        */

        // 2.使用Arrays.copyOf()方法复制
        //char[] result = Arrays.copyOf(value, temp.length + value.length);

        // 3.使用System.arraycopy()方法复制
        char[] result = new char[value.length + temp.length];
        System.arraycopy(value,0,result,0,value.length);
        System.arraycopy(temp,0,result,value.length,temp.length);

        value = result;
        return this;
    }

    public void print() {
        for (int i = 0; i < value.length; i++) {
            System.out.print(value[i]);
        }
        System.out.println();
    }
}
